<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #menu="{ model, field }">
        <BasicTree
          v-model:value="model[field]"
          :treeData="treeData"
          :fieldNames="{ title: 'title', key: 'id' }"
          checkable
          toolbar
          title="菜单分配"
          @check="onCheck"
        />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './role.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicTree, TreeItem } from '/@/components/Tree';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getMenuList } from '/@/api/sys/resources';
  import { searchRole, updateRole, createRole } from '/@/api/sys/role';
  export default defineComponent({
    name: 'RoleDrawer',
    components: { BasicDrawer, BasicForm, BasicTree },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const treeData = ref<TreeItem[]>([]);
      const rowId = ref('');
      const { createMessage } = useMessage();
      const menusList = ref([]);
      const newMenusList = ref([]);
      const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
        labelWidth: 90,
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        // 需要在setFieldsValue之前先填充treeData，否则Tree组件可能会报key not exist警告
        if (unref(treeData).length === 0) {
          treeData.value = (await getMenuList()) as any as TreeItem[];
        }
        isUpdate.value = !!data?.isUpdate;

        if (unref(isUpdate)) {
          rowId.value = data.record.id;
          const records = await searchRole(rowId.value);
          menusList.value = records.menu;
          newMenusList.value = records.menu;
          setFieldsValue({
            ...records,
          });
        }
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增角色' : '编辑角色'));

      function checkSame(a, b) {
        if (a.length !== b.length) {
          return false;
        } else {
          for (let index = 0; index < a.length; index++) {
            const element = a[index];
            if (b.indexOf(element) == -1) {
              return false;
            }
          }
        }
        return true;
      }

      async function handleSubmit() {
        try {
          const values = await validate();
          setDrawerProps({ confirmLoading: true });
          var success;
          values.id = unref(rowId);

          //判断新旧节点列表元素是否完全一致 完全一致不修改资源列表
          if (checkSame(menusList.value, newMenusList.value)) {
            delete values.menu;
          } else {
            values.menu = newMenusList.value;
          }

          if (unref(isUpdate)) {
            success = updateRole(values);
            //成功之后才能关闭界面
            success.then(() => {
              createMessage.success('操作成功');
              closeDrawer();
              emit('success');
            });
          } else {
            success = createRole(values);
            //成功之后才能关闭界面
            success.then(() => {
              createMessage.success('操作成功');
              closeDrawer();
              emit('success');
            });
          }
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      function onCheck(a, b) {
        //每次赋值前清空
        newMenusList.value = [];
        for (let index = 0; index < a.length; index++) {
          const element = a[index];
          newMenusList.value.push(element);
        }
        for (let index = 0; index < b.halfCheckedKeys.length; index++) {
          const element = b.halfCheckedKeys[index];
          newMenusList.value.push(element);
        }
      }

      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
        treeData,
        onCheck,
      };
    },
  });
</script>
